//
//  GSGFDBViewController.m
//  Estate
//
//  Created by heyong on 16/5/26.
//  Copyright © 2016年 ttsx. All rights reserved.
//
#define DIC_EXPANDED @"expanded" //是否是展开 0收缩 1展开
#define DIC_ARARRY @"array"
#define DIC_TITILESTRING @"title"
#define CELL_HEIGHT 46.0f
#define TIME @"date"
#import "RJTableCell.h"
#import "JLJLTableCell.h"
#import "GSGFDBViewController.h"
#import "addJGDBViewController.h"
#import "FMResultSet.h"
#import "ProcessModel.h"
#import "FollowInCell.h"
#import "SGFDBDetailViewController.h"

@interface GSGFDBViewController ()

@end

@implementation GSGFDBViewController

-(UITableView *)tableView{
    
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-44-49-50*BIZ)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        [_tableView registerNib:[UINib nibWithNibName:@"FollowInCell" bundle:nil] forCellReuseIdentifier:@"FICell"];
        [_tableView registerNib:[UINib nibWithNibName:@"JLJLTableCell" bundle:nil] forCellReuseIdentifier:@"JLJLCell"];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    self.view.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    self.tableView.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    [self initDataSource];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sgfDaiBReloadData) name:@"sgfDaiB" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sgfDaiBReloadData) name:@"reloadData" object:nil];
}


- (void)sgfDaiBReloadData {
    [self.DataArray removeAllObjects];
    [self initDataSource];
    [self.tableView reloadData];
}


// 初始化数据
- (void)initDataSource
{
    // 初始化数组
    _DataArray=[[NSMutableArray alloc] init];
    // 获取项目ID
    NSString *proID = DEF_PERSISTENT_GET_OBJECT(@"proid");
    // 获取用户ID
    NSString *userID = DEF_PERSISTENT_GET_OBJECT(@"userid");
    // 准备sql语句
    NSString *Str = [NSString stringWithFormat:@"SELECT COUNT(*), date(CREATE_TIME) FROM PROCESS WHERE PRO_ID = '%@' AND PROCESS_RECIFY_USERS = '%@' AND PROCESS_STAGE NOT IN(202, 5, 2) AND PROCESS_TYPE != '3' GROUP BY date(CREATE_TIME) ORDER BY date(CREATE_TIME) desc", proID, userID];
//    NSLog(@"%@", Str);
    
    // 查询数据
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result=[db executeQuery:Str];
    NSMutableDictionary *dic;
    while ([result next]) {
        //  查询日期
        NSString *date= [result stringForColumn:@"date(CREATE_TIME)"];
        
        // 根据日期查询展开的数据
        NSString *sqlStr=[NSString stringWithFormat:@"SELECT *, date(CREATE_TIME), time(CREATE_TIME) FROM PROCESS WHERE PRO_ID = '%@' AND date(CREATE_TIME) = '%@' AND PROCESS_RECIFY_USERS = '%@' AND PROCESS_STAGE NOT IN(202, 5, 2) AND PROCESS_TYPE != '3' ORDER BY time(CREATE_TIME) desc", proID, date, userID];
//        NSLog(@"---------------%@",sqlStr);
        FMResultSet *results=[db executeQuery:sqlStr];
        //查询到记录
        NSMutableArray *modelArr=[NSMutableArray array];
        while ([results next]) {
            ProcessModel *model=[[ProcessModel alloc]init];
            
            model.ID=[results stringForColumn:@"ID"];
            model.PRO_ID=[results stringForColumn:@"PRO_ID"];
            model.ADDRESS_ID=[results stringForColumn:@"ADDRESS_ID"];
            model.ADDRES_INFO=[results stringForColumn:@"ADDRES_INFO"];
            model.PROCESS_TYPE=[results intForColumn:@"PROCESS_TYPE"];
            model.PROCESS_STAGE=[results intForColumn:@"PROCESS_STAGE"];
            model.PROCESS_PUBLISHERS = [results stringForColumn:@"PROCESS_PUBLISHERS"];
            model.PROCESS_MASTERS=[results stringForColumn:@"PROCESS_MASTERS"];
            model.PROCESS_RECIFY_USERS = [results stringForColumn:@"PROCESS_RECIFY_USERS"];
            model.PROCESS_RECIFY_UNITS = [results stringForColumn:@"PROCESS_RECIFY_UNITS"];
            model.RECIFY_REVIEW_USERS = [results stringForColumn:@"RECIFY_REVIEW_USERS"];
            model.BEGIN_TIME = [results stringForColumn:@"BEGIN_TIME"];
            model.REQUIRED_END_TIME = [results stringForColumn:@"REQUIRED_END_TIME"];
            model.END_TIME = [results stringForColumn:@"END_TIME"];
            model.PROCESS_TITLE = [results stringForColumn:@"PROCESS_TITLE"];
            model.PROCESS_NUMBER = [results stringForColumn:@"PROCESS_NUMBER"];
            model.EXTEND_INFO = [results stringForColumn:@"EXTEND_INFO"];
            model.CREATE_USER_NAME = [results stringForColumn:@"CREATE_USER_NAME"];
            model.CREATE_TIME = [results stringForColumn:@"CREATE_TIME"];
            model.CREATE_DATE = [results stringForColumn:@"date(CREATE_TIME)"];
            model.CREATE_DETAIL_TIME = [results stringForColumn:@"time(CREATE_TIME)"];
            model.CREATE_IP = [results stringForColumn:@"CREATE_IP"];
            model.MODIFY_USER_NAME = [results stringForColumn:@"MODIFY_USER_NAME"];
            model.MODIFY_IP = [results stringForColumn:@"MODIFY_IP"];
            model.MODIFY_TIME = [results stringForColumn:@"MODIFY_TIME"];
            
            [modelArr addObject:model];
        }
        // 查询到数量
        NSString *counts=[result stringForColumn:@"COUNT(*)"];
        // 拼接成标题
        NSString *tiemAndCount=[date stringByAppendingString:[NSString stringWithFormat:@"\t(%@条)",counts]];
        // 创建一个字典 包含数组，分组名，是否展开的标示
        dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:modelArr,DIC_ARARRY,tiemAndCount,DIC_TITILESTRING,[NSNumber numberWithInt:0],DIC_EXPANDED,nil];
        // 将字典加入数组
        [self.DataArray addObject:dic];
    }
    [db close];
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _DataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic=[_DataArray objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FollowInCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FICell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    long section = indexPath.section;
    long row = indexPath.row;
    
    // 得到改组下信息
    NSMutableDictionary *dic = [self.DataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    ProcessModel *model = array[row];
    
    //时差
    NSString *shicha;
    if ([model.REQUIRED_END_TIME isEqual:@""]) {
        shicha = @"0";
    } else {
        NSTimeInterval  timeInterval = [LSUtility getDifftimeByTime:model.REQUIRED_END_TIME];
        long temp = timeInterval / 3600;
        if (timeInterval >= 0) {
            temp = temp + 1;
        } else if (timeInterval < 0) {
            temp = temp - 1;
        }
        shicha = [NSString stringWithFormat:@"%ld", temp];
    }
    shicha = [shicha stringByAppendingString:@"H"];
    
    [cell setTitle:model.PROCESS_TITLE andDeTime:model.CREATE_DETAIL_TIME andTime:shicha andState:(int)model.PROCESS_STAGE andProcessType:(int)model.PROCESS_TYPE];
    return cell;
}

//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH, CELL_HEIGHT-10)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    
    //设置分组标题
    [eButton setTitle:[[_DataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:14.*BIZ];
    
    //设置button的图片和标题的相对位置
    
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0,5, 0,0)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(5,DEF_SCREEN_WIDTH-30, 0,0)];
    
    //添加btn
    [hView addSubview: eButton];
    return hView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[_DataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 10;
    }else{
        return 0;
    }
}

//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46*BIZ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70*BIZ;
    
}
#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section=indexPath.section;
    NSInteger row=indexPath.row;
    // 跳转到待办详情页面
    SGFDBDetailViewController *detail=[[SGFDBDetailViewController alloc]init];
    detail.flag=@"detail";
    detail.edit = NO;
    detail.daiBDetail = YES;
    // 流程模型
    ProcessModel *pModel = [[self.DataArray objectAtIndex:section] objectForKey:DIC_ARARRY][row];
    detail.processID = pModel.ID;
    detail.pModel = pModel;
    detail.addressInfo = pModel.ADDRES_INFO;
    detail.beginTime = pModel.BEGIN_TIME;
    [self.navigationController pushViewController:detail animated:YES];
}

#pragma mark -- 内部调用

//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section{
    NSMutableDictionary *dic=[_DataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
    }else
    {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
    
}

//返回指定节是否是展开的

-(int)isExpanded:(long)section{
    NSDictionary *dic=[_DataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

//按钮被点击时触发
-(void)expandButtonClicked:(id)sender{
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
